package trade.service.impl;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import trade.bean.TCashierTrade;
import trade.cutil.RestHttpUtil;
import trade.dao.TCashierTradeMapper;
import trade.service.ITCashierTradeService;

import java.util.HashMap;
import java.util.Map;

/**
 * service层统一处理业务       
 */
@Service
public class TCashierTradeServiceImpl implements ITCashierTradeService {

    @Value("${version}")
    String version;

    //service层进行微服务调用
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    TCashierTradeMapper tradeMapper;

    @Override
    public String insertTrade(TCashierTrade trade) {
        Map map = new HashMap();
        try {
            tradeMapper.insertTrade(trade);
        } catch (Exception e) {
            return getResponse(map);
        }
        map.put("respCode","0000");
        map.put("respDesc","插入交易信息成功");
        JSONObject jsonObject = new JSONObject(map);
        return jsonObject.toString();
    }

    @Override
    public String updateTrade(TCashierTrade trade) {
        Map map = new HashMap();
        try {
            tradeMapper.updateTrade(trade);
        } catch (Exception e) {
            return getResponse(map);
        }
        map.put("respCode","0000");
        map.put("respDesc","更新交易信息成功");
        JSONObject jsonObject = new JSONObject(map);
        return jsonObject.toString();
    }

    //代码去重
    public String getResponse(Map map) {
        map.put("respCode","0001");
        map.put("respDesc", RestHttpUtil
                .postHttp(restTemplate ,"http://ErrorSys/ErrorSys/" + version + "/getTradeSysCode/{code}","0001"));
        JSONObject jsonObject = new JSONObject(map);
        return jsonObject.toString();
    }

    @Override
    public String selectTrade(String orderId) {
        TCashierTrade cashierTrade = tradeMapper.selectTrade(orderId);
        Map map = new HashMap();
        map.put("respCode","0000");
        map.put("respDesc","查询交易信息成功");
        map.put("tradeInfo", new JSONObject(cashierTrade).toString());
        return new JSONObject(map).toString();
    }
}
